<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="rolestList" style="width: 100%" border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 渲染 -->
            <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id"
              :class="['bdbottom',i1===0?'bdtop':'','vcenter']">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right" />
              </el-col>
              <!-- 二级权限，三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级 -->
                <el-row :class="[i2===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right" />
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3,i3) in item2.children" :key="item3.id" closable
                      @close="removeRightById(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="序号" width="100%" />
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column prop="roleDesc" label="角色描述" />
        <el-table-column prop="level" label="操作" width="295px">
          <template slot-scope="scope">
            <el-button icon="el-icon-edit" type="primary" size="mini">编辑
            </el-button>
            <el-button icon="el-icon-delete" type="danger" size="mini">删除
            </el-button>
            <el-button icon="el-icon-setting" type="warning" size="mini" @click="showSetRightDialog(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="提示" :visible.sync="SetRightDialogVisible" width="30%">
      <el-tree ref="treeRef" :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all
        :default-checked-keys="defKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      rolestList: [],
      rightsList: [],
      //树形控件
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //默认选择
      defKeys: [],
      SetRightDialogVisible: false,
      roleId: ''
    }
  },
  //生命周期
  created () {
    this.getRolestList()
  },
  methods: {
    async getRolestList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表数据失败')
      }
      this.rolestList = res.data
    },
    async removeRightById (role, rightId) {
      const result = await this.$confirm('此操作将永久删除权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除数据失败')
      }
      this.$message.success('删除权限成功')
      //   this.getRolestList()
      role.children = res.data
    },
    //展开分配权限对话框
    async showSetRightDialog (role, roleId) {
      this.roleId = role.id
      //获取所有权限数据
      const { data: res } = await this.$http.get('rights/tree')
      //
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      //   把获取的数据权限保存到data中
      this.rightsList = res.data
      this.getLeafKeys(role, this.defKeys)
      this.SetRightDialogVisible = true
    },
    //通过递归的形式获取角色项，所有三级菜单的id，保存到key数组中
    getLeafKeys (node, arr) {
      //如果当前node节点不包含children，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      });
    },
    async allotRight () {
      const keys = [
        ...this.$refs.treeRef.
          getCheckedKeys(),
        //展开运算符
        ...this.$refs.treeRef.
          getHalfCheckedKeys()
      ]
      console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        this.$message.error('获取权限数据失败')
      }
      this.$message.success('新增权限数据成功')
      this.getRolestList()
      this.SetRightDialogVisible = false
    }
  }
}
</script>
<style scoped>
.el-table {
  margin-top: 15px;
  font-size: 15px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>